﻿using CuoDing.Core.DAL;
using CuoDing.Core.Model;
using CuoDing.Core.Model.Enum;
using CuoDing.Core.Model.Model;
using CuoDing.Core.Model.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace CuoDing.Core.BLL
{
    public class SystemUserBLL : ISystemUserBLL
    {
        private readonly SystemUserDAL _dal;

        /// <summary>
        /// 构造函数注入
        /// </summary>
        /// <param name="dal"></param>
        public SystemUserBLL(SystemUserDAL dal)
        {
            _dal = dal;
        }

        /// <summary>
        /// 添加用户
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public async Task<DXResult> AddUsers(SystemUser model)
        {
            DXResult dXResult = new DXResult();

            int i = await _dal.UpdateOrInsert(model);
            if (i > 0)
            {
                dXResult.code = DXCode.Success;
            }
            else
                dXResult.code = DXCode.Failure;
            return dXResult;
        }
        /// <summary>
        /// 获取用户
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<SystemUser> GetUser(long id)
        {
            SystemUser dXResult = await _dal.GetById(id);
            return dXResult;
        }


        /// <summary>
        /// 更新用户（事务）
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        public DXResult Update(SystemUser param)
        {
            DXResult dXResult = new DXResult();

            try
            {
                //注意：Transaction不支持异步编程
                _dal.fsql.Transaction(() =>
                {
                    param.ModifyTime = DateTime.Now;
                    //更新用户表
                    dXResult.count = _dal.fsql.Update<SystemUser>().SetSource(param)
                        .IgnoreColumns(it => new { it.CreateTime })
                        .ExecuteAffrows();
                    //更新其他关联表
                    _dal.fsql.Ado.ExecuteNonQuery(string.Format("UPDATE TEST_USER SET ModifyTime=sysdate WHERE USERID='{0}'", param.Id));

                    if (dXResult.count < 1)
                        throw new Exception("数据修改失败");
                    dXResult.code = DXCode.Success;
                    dXResult.msg = "数据已修改";
                });
            }
            catch (Exception ex)
            {
                dXResult.code = DXCode.Failure;
                dXResult.msg = ex.Message;
            }

            return dXResult;
        }

        /// <summary>
        /// 系统登录(token专用)
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public async Task<DXResult> LoginToken(SystemUser param)
        {
            DXResult dXResult = new DXResult();
            dXResult.code = DXCode.Success;
            dXResult.msg = "登录成功";
            try
            {
                #region 验证条件
                if (string.IsNullOrEmpty(param.UserCode))
                {
                    dXResult.code = DXCode.BadRequest;
                    dXResult.msg = "请输入工号";
                    return dXResult;
                }
                else if (string.IsNullOrEmpty(param.Password))
                {
                    dXResult.code = DXCode.BadRequest;
                    dXResult.msg = "请输入密码";
                    return dXResult;
                }

                var user = await _dal.fsql.Select<SystemUser>().Where(it => it.UserCode == param.UserCode&&it.Password==param.Password).FirstAsync();

                if (user == null)
                {
                    dXResult.code = DXCode.Failure;
                    dXResult.msg = "账号未注册";
                    return dXResult;
                }
                else if (user.DeleteMark.Value)
                {
                    dXResult.code = DXCode.Failure;
                    dXResult.msg = "账号已删除";
                    return dXResult;
                }
                else
                {

                    dXResult.data = user;
                }
                #endregion

            }
            catch (Exception ex)
            {
                dXResult.code = DXCode.Failure;
                dXResult.msg = ex.Message;
            }
            return dXResult;
        }

        /// <summary>
        /// 获取用户详情(token专用)
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<DXResult> TokenGetById(long id)
        {
            DXResult dXResult = new DXResult();
            dXResult.code = DXCode.Success;
            dXResult.msg = "获取成功";
            try
            {
                SystemUser user = await _dal.GetById(id);
                if (!user.Id.HasValue)
                {
                    dXResult.code = DXCode.Failure;
                    dXResult.msg = "未找到该用户信息";
                    return dXResult;
                }
                dXResult.data = user;
            }
            catch (Exception ex)
            {
                dXResult.code = DXCode.Failure;
                dXResult.msg = ex.Message;
            }
            return dXResult;
        }
    }
}
